#!/bin/bash

function print_help()
{
    pgm=`basename $0`
    echo "\"$pgm\" usage:"
    echo "  $pgm query EventID"
}

function query_event()
{
    QueryID="$1"
    SQLFILE="`dirname $0`/qcedb_event.sql"
    EVENTID="__EVENT_ID__"
    LEGACYID="__LEGACY_ID__"
    SQLFILETMP=$SQLFILE.tmp
    
    # namearr=(None $(cat $SQLFILE | awk -F' AS ' '(NF>=2){gsub("^ +", "", $2);gsub(" +$", "", $2);gsub(",", "", $2);printf("%s ",$2)}'))
    
    # Build a name array based on the SQL select names
    arrstr=`cat $SQLFILE | awk -F' AS ' '(NF>=2){gsub("^ +", "", $2);gsub(" +$", "", $2);gsub(",", "", $2);printf("%s|",$2)}'`
    
    # Replace the keyword "$EVENT_ID" with the actual value we are querying
    QueryStrID="$QueryID"
    QueryIntID=`echo $QueryID | awk '{if ($0 ~ /^[0-9]+$/) {print $0;} else {print 0}}'`
    cat $SQLFILE | awk '{gsub("'"$EVENTID"'", "'"$QueryIntID"'",  $0);gsub("'"$LEGACYID"'", "'"$QueryStrID"'",  $0);print $0}' > $SQLFILETMP
    
    # Execute the SQL and print result
    sqlplus EGUEST/EGUEST@cedb.cup.hp.com:1521/CCODE @$SQLFILETMP | awk -F '|' '{\
      if (NF > 10) {\
        arrstr="'"$arrstr"'";\
        split(arrstr, namearr, "|" );
        for (i=1;i<=NF;i++) {\
          gsub(/^[ |\t]+|[ |\t]+$/, "", $i);\
          printf("%-15s: %s\n", namearr[i], $i);\
        }\
        printf("\n\n");\
      }\
    }'
    rm -f $SQLFILETMP
}

cmd="$1"
param="$2"

[ "$cmd" == "help" ] && print_help && exit 0
[ "$cmd" == "query" ] && query_event "$param" && exit 0

rlwrap sqlplus EGUEST/EGUEST@cedb.cup.hp.com:1521/CCODE


